﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using EntityDA;
using BussinessObject;

public partial class GioHang : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        MyList List = (MyList)Session["GioHang"];
        GridView.DataSource = List;
        GridView.DataBind();
    }

    protected void btnUpDate_Click(object sender, EventArgs e)
    {
        LinkButton btnUpdate = (LinkButton)sender;
        int MaSach = Int32.Parse(btnUpdate.CommandArgument.ToString()); //lấy mã sách
        MyList List = (MyList)Session["GioHang"];
        CartItem item = new CartItem();
        item.MaSach = MaSach;
        List.UpdateCart(item, 1);
        GridView.DataSource = List;
        Label2.Text = List.TongCart().ToString();
        GridView.DataBind();
    }
    protected void btnXoa_Click(object sender, EventArgs e)
    {
        LinkButton btnXoa = (LinkButton)sender;
        int MaSach = Int32.Parse(btnXoa.CommandArgument.ToString());
        MyList List = (MyList)Session["GioHang"];

        CartItem item = new CartItem();
        item.MaSach = MaSach;
        List.Remove(item);//xóa sp khỏi giỏ hàng
        GridView.DataSource = List;
        Label2.Text = List.TongCart().ToString();
        GridView.DataBind();
    }
    protected void Label2_Load(object sender, EventArgs e)
    {
        Label la = (Label)sender;
        MyList list = (MyList)Session["GioHang"];
        if (list != null)
        {
            la.Text = list.TongCart().ToString();
        }
    }

    protected void btnThanhToan_Click(object sender, EventArgs e)
    {
        MyList List = (MyList)Session["GioHang"];
        HoaDonDB db = new HoaDonDB();
        HoaDonData data = new HoaDonData();
        data.MaTV = 1;//giả sử
        data.DiaChiGH = "HCM";//giả sử để test
        if (db.ThemHoaDon(data))
        {
            data.MaHD = db.GetOneHoaDon(1).MaHD;
            ChiTietHoaDonData CTHDdata = new ChiTietHoaDonData();
            foreach (CartItem item in List)
            {
                ChiTietHoaDonDB CTHDdb = new ChiTietHoaDonDB();
                CTHDdata.MaHD = data.MaHD;
                CTHDdata.MaSach = item.MaSach;
                CTHDdata.SL = item.SoLuong;
                CTHDdata.DonGia = item.Gia;
                CTHDdb.ThemCTHD(CTHDdata);//thêm chi tiết hoá đơn
            }
            Session["GioHang"] = null;//mua xong phải xoá giỏ hàng            
            GridView.DataBind();//refesh lai cart tren giao diên
        }
    }
}
